package com.plusjun.gulimall.order.web;

import com.plusjun.gulimall.order.service.OrderService;
import com.plusjun.gulimall.order.vo.OrderConfirmVO;
import com.plusjun.gulimall.order.vo.OrderSubmitVO;
import com.plusjun.gulimall.order.vo.SubmitOrderResponseVO;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebController {

    @Resource
    OrderService orderService;

    /**
     * 跳往订单确认页
     *
     * @return
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model) {

        OrderConfirmVO confirmVO = null;
        try {
            confirmVO = orderService.confirmOrder();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        model.addAttribute("orderConfirmData", confirmVO);

        return "confirm";
    }

    /**
     * 下单功能
     *
     * @param orderSubmitVO
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVO orderSubmitVO, Model model, RedirectAttributes redirectAttributes) {
        // 下单：创建订单、验证令牌、验价格、锁库存。。。
        SubmitOrderResponseVO responseVO = null;
            responseVO = orderService.submitOrder(orderSubmitVO);
        if (responseVO.getCode() == 0) {
            // 下单成功，来到支付页
            model.addAttribute("submitOrderResponse", responseVO);
            return "pay";
        } else {
            StringBuffer msg = new StringBuffer("下单失败：");
            switch (responseVO.getCode()) {
                case 1:
                    msg.append("订单信息过期，请刷新再次提交");
                    break;
                case 2:
                    msg.append("订单商品价格发送变化，请刷新再次提交");
                    break;
                case 3:
                    msg.append("库存锁定失败，商品库存不足");
                    break;
            }
            redirectAttributes.addAttribute("msg",msg);
            return "redirect:http://order.gulimall.com/toTrade";
        }
    }
}
